const { createApp } = Vue;

createApp({
    data() {
        return {
            searchKey: '',
            statistics: {
                status_0: 0,
                status_1: 0,
                status_2: 0,
                status_3: 0,
                status_4: 0,
                status_5: 0
            },
            form: {
                templateId: '',
                content: ''
            },
            templates: [],
            releaseList: [],
            uploading: false,
            uploadProgress: 0,
            currentUploadIndex: 0,
            totalUploadCount: 0,
            addModal: null,
            selectedTemplate: '',
            currentPage: 1,
            pageSize: 20,
            totalReleases: 0,
            filter: {
                templateId: '',
                status: ''
            },
            selectedItems: [],
            statusOptions: [
                { value: '', label: '全部' },
                { value: '0', label: '未使用' },
                { value: '1', label: '占用中' },
                { value: '2', label: '待审核' },
                { value: '3', label: '已通过' },
                { value: '4', label: '已拒绝' },
                { value: '5', label: '异常' }
            ]
        }
    },
    computed: {
        regexPreview() {
            if (!this.formData.regex || !this.form.content) return '';
            
            // 获取第一条数据
            const firstLine = this.form.content.split('\n')[0]?.trim();
            if (!firstLine) return '';

            try {
                const regex = new RegExp(this.formData.regex);
                const match = firstLine.match(regex);
                if (match && match[1]) {
                    return match[1];
                }
                return '无匹配结果';
            } catch (error) {
                return '正则表达式无效';
            }
        },
        selectAll: {
            get() {
                return this.releaseList.length > 0 && this.selectedItems.length === this.releaseList.length;
            },
            set(value) {
                this.selectedItems = value ? this.releaseList.map(item => item.id) : [];
            }
        }
    },
    methods: {
        // 获取统计数据
        async getStatistics() {
            try {
                const res = await fetch('/api/admin/statistics');
                const data = await res.json();
                if (data.code === 200) {
                    this.statistics = data.data;
                }
            } catch (error) {
                console.error('获取统计数据失败:', error);
            }
        },

        // 显示添加弹窗
        showAddDialog() {
            this.form.templateId = '';
            this.form.content = '';
            this.addModal.show();
        },

        // 获取模板列表
        async getTemplates() {
            try {
                const res = await fetch('/api/admin/templates');
                const data = await res.json();
                if (data.code === 200) {
                    this.templates = data.data;
                }
            } catch (error) {
                console.error('获取模板列表失败:', error);
            }
        },

   

        // 搜索爆料
        searchReleases() {
            this.getReleaseList();
        },

        // 提交数据
        async submitData() {
            if (!this.form.templateId) {
                Swal.fire({
                    icon: 'warning',
                    title: '请选择模板'
                });
                return;
            }
            if (!this.form.content.trim()) {
                Swal.fire({
                    icon: 'warning',
                    title: '请输入爆料内容'
                });
                return;
            }

            const dataList = this.form.content.split('\n').filter(item => item.trim());
            if (dataList.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: '没有有效的爆料内容'
                });
                return;
            }

            this.uploading = true;
            this.uploadProgress = 0;
            this.currentUploadIndex = 0;
            this.totalUploadCount = dataList.length;

            try {
                for (let data of dataList) {
                    await fetch('/api/admin/release', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            template_id: this.form.templateId,
                            data: data.trim()
                        })
                    });
                    
                    this.currentUploadIndex++;
                    this.uploadProgress = Math.floor((this.currentUploadIndex / this.totalUploadCount) * 100);
                }

                this.uploading = false;
                this.addModal.hide();
                
                Swal.fire({
                    icon: 'success',
                    title: '上传完成',
                    showConfirmButton: false,
                    timer: 1500
                });

                this.getStatistics();
                //this.getReleaseList();
                this.form.content = '';
            } catch (error) {
                console.error('上传失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '上传失败',
                    text: error.message || '请重试'
                });
                this.uploading = false;
            }
        },

        // 删除爆料
        async handleDelete(item) {
            const result = await Swal.fire({
                title: '确认删除？',
                text: '此操作不可恢复！',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6'
            });

            if (result.isConfirmed) {
                try {
                    const res = await fetch(`/api/admin/release/delete?id=${item.id}`, {
                        method: 'DELETE'
                    });
                    const data = await res.json();
                    if (data.code === 200) {
                        Swal.fire({
                            icon: 'success',
                            title: '删除成功',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        this.getReleaseList();
                        this.getStatistics();
                    } else {
                        throw new Error(data.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '删除失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },

        // 计算占用时间
        getOccupyTime(callTime) {
            if (!callTime) return '';
            
            const startTime = new Date(callTime).getTime();
            const now = new Date().getTime();
            const diffMinutes = Math.floor((now - startTime) / (1000 * 60));
            
            if (diffMinutes < 1) {
                return '刚刚开始';
            } else if (diffMinutes < 60) {
                return `${diffMinutes}分钟`;
            } else {
                const hours = Math.floor(diffMinutes / 60);
                const minutes = diffMinutes % 60;
                return `${hours}小时${minutes}分钟`;
            }
        },

        // 获取状态文字
        getStatusText(status) {
            const statusMap = {
                '0': '未使用',
                '1': '占用中',
                '2': '待审核',
                '3': '已通过',
                '4': '已拒绝',
                '5': '数据异常'
            };
            return statusMap[status] || '未知状态';
        },

        // 获取状态样式
        getStatusClass(status) {
            const classMap = {
                '0': 'bg-secondary',
                '1': 'bg-primary',
                '2': 'bg-warning',
                '3': 'bg-success',
                '4': 'bg-danger',
                '5': 'bg-dark'
            };
            return classMap[status] || 'bg-secondary';
        },

        async handleSubmit() {
            if (!this.formData.template_id) {
                Swal.fire({
                    icon: 'warning',
                    title: '请选择模板'
                });
                return;
            }

            if (!this.formData.data?.trim()) {
                Swal.fire({
                    icon: 'warning',
                    title: '请输入数据'
                });
                return;
            }

            try {
                const response = await fetch('/api/admin/release', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        template_id: this.formData.template_id,
                        data: this.formData.data,
                        regex: this.formData.regex
                    })
                });

                const data = await response.json();
                if (data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '发布成功',
                        showConfirmButton: false,
                        timer: 1500
                    });
                    // 重置表单
                    this.formData.data = '';
                    this.formData.regex = '';
                } else {
                    throw new Error(data.msg || '发布失败');
                }
            } catch (error) {
                console.error('发布失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '发布失败',
                    text: error.message || '请重试'
                });
            }
        },

        async loadTemplates() {
            try {
                const response = await fetch('/api/admin/templates');
                const data = await response.json();
                if (data.code === 200) {
                    this.templates = data.data;
                }
            } catch (error) {
                console.error('加载模板列表失败:', error);
            }
        },

        async loadReleases() {
            try {
                const params = new URLSearchParams({
                    page: this.currentPage,
                    size: this.pageSize,
                    template_id: this.filter.templateId,
                    status: this.filter.status
                });
                
                const response = await fetch(`/api/admin/releases?${params}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    this.totalReleases = data.total;
                    this.releaseList = data.data;
                }
            } catch (error) {
                console.error('加载爆料数据失败:', error);
            }
        },

        handleSelectAll(e) {
            if (e.target.checked) {
                this.selectedItems = this.releaseList.map(item => item.id);
            } else {
                this.selectedItems = [];
            }
        },

        async handleBatchDelete() {
            const result = await Swal.fire({
                title: '确认删除',
                text: `确定要删除选中的 ${this.selectedItems.length} 条记录吗？`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonColor: '#dc3545'
            });

            if (result.isConfirmed) {
                try {
                    const response = await fetch('/api/admin/releases/batch', {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            ids: this.selectedItems
                        })
                    });

                    const data = await response.json();
                    if (data.code === 200) {
                        Swal.fire({
                            icon: 'success',
                            title: '删除成功',
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        this.selectedItems = [];
                        this.loadReleases();
                    }
                } catch (error) {
                    console.error('批量删除失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '删除失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },

        async handleBatchReset() {
            const result = await Swal.fire({
                title: '确认重置',
                text: `确定要重置选中的 ${this.selectedItems.length} 条记录吗？`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定重置',
                cancelButtonText: '取消',
                confirmButtonColor: '#ffc107'
            });

            if (result.isConfirmed) {
                try {
                    const response = await fetch('/api/admin/releases/batch/reset', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            ids: this.selectedItems
                        })
                    });

                    const data = await response.json();
                    if (data.code === 200) {
                        Swal.fire({
                            icon: 'success',
                            title: '重置成功',
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        this.selectedItems = [];
                        this.loadReleases();
                    }
                } catch (error) {
                    console.error('批量重置失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '重置失败',
                        text: error.message || '请重试'
                    });
                }
            }
        }
    },
    watch: {
        'filter.templateId'() {
            this.currentPage = 1;
            this.loadReleases();
        },
        'filter.status'() {
            this.currentPage = 1;
            this.loadReleases();
        }
    },
    mounted() {
        this.addModal = new bootstrap.Modal(document.getElementById('addReleaseModal'));
        this.getStatistics();
        this.getTemplates();
        this.loadTemplates();
        this.loadReleases();
    }
}).mount('#releaseApp');